package com.xscha.tableforge.repository;

import com.xscha.soyue.common.core.utils.DateUtils;
import com.xscha.tableforge.model.entity.TableMeta;
import com.xscha.tableforge.model.vo.PageReq;
import org.jooq.DSLContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.jooq.OrderField;
import org.jooq.Field;

import java.util.ArrayList;
import com.xscha.tableforge.model.vo.PageResult;
import java.util.List;
import java.util.Optional;

import static com.xscha.tableforge.jooq.tables.TableMetaTable.TABLE_META;
import static org.jooq.impl.DSL.*;

@Repository
public class TableMetaRepository {

    private final DSLContext dslContext;

    @Autowired
    public TableMetaRepository(DSLContext dslContext) {
        this.dslContext = dslContext;
    }

    public List<TableMeta> findAllByAppId(String appId) {
        return dslContext.select()
                .from(TABLE_META)
                .where(TABLE_META.APP_ID.eq(appId)
                        .and(TABLE_META.DELETED_TIME.isNull()))
                .orderBy(TABLE_META.CREATED_TIME.asc())
                .fetchInto(TableMeta.class);
    }

    public Optional<TableMeta> findById(String id) {
        return dslContext.select()
                .from(TABLE_META)
                .where(TABLE_META.ID.eq(id)
                        .and(TABLE_META.DELETED_TIME.isNull()))
                .fetchOptionalInto(TableMeta.class);
    }

    public TableMeta save(TableMeta tableMeta) {
        dslContext.insertInto(TABLE_META)
                .set(TABLE_META.ID, tableMeta.getId())
                .set(TABLE_META.APP_ID, tableMeta.getAppId())
                .set(TABLE_META.NAME, tableMeta.getName())
                .set(TABLE_META.DESCRIPTION, tableMeta.getDescription())
                .set(TABLE_META.ICON, tableMeta.getIcon())
                .set(TABLE_META.DB_TABLE_NAME, tableMeta.getDbTableName())
                .set(TABLE_META.VERSION, tableMeta.getVersion())
                .set(TABLE_META.DISPLAY_ORDER, tableMeta.getDisplayOrder())
                .set(TABLE_META.CREATED_TIME, tableMeta.getCreatedTime())
                .set(TABLE_META.CREATED_BY, tableMeta.getCreatedBy())
                .execute();
        return tableMeta;
    }

    public TableMeta update(TableMeta tableMeta) {
        dslContext.update(TABLE_META)
                .set(TABLE_META.NAME, tableMeta.getName())
                .set(TABLE_META.DESCRIPTION, tableMeta.getDescription())
                .set(TABLE_META.ICON, tableMeta.getIcon())
                .set(TABLE_META.VERSION, tableMeta.getVersion())
                .set(TABLE_META.LAST_MODIFIED_BY, tableMeta.getLastModifiedBy())
                .set(TABLE_META.LAST_MODIFIED_TIME, tableMeta.getLastModifiedTime())
                .where(TABLE_META.ID.eq(tableMeta.getId()))
                .execute();
        return tableMeta;
    }

    public void softDelete(String id, String userId) {
        dslContext.update(TABLE_META)
                .set(TABLE_META.DELETED_TIME, DateUtils.nowTimeStamp().toLocalDateTime())
                .set(TABLE_META.LAST_MODIFIED_BY, userId)
                .set(TABLE_META.LAST_MODIFIED_TIME, DateUtils.nowTimeStamp().toLocalDateTime())
                .where(TABLE_META.ID.eq(id))
                .execute();
    }

    public PageResult<TableMeta> findPageByAppId(String appId, PageReq pageRequest) {
        // 计算总记录数
        int total = dslContext.selectCount()
                .from(TABLE_META)
                .where(TABLE_META.APP_ID.eq(appId)
                        .and(TABLE_META.DELETED_TIME.isNull()))
                .fetchOneInto(Integer.class);
        
        // 构建排序条件
        List<OrderField<?>> orderFields = new ArrayList<>();
        if (pageRequest.getOrderBy() != null && !pageRequest.getOrderBy().isEmpty()) {
            Field<?> orderField = TABLE_META.field(pageRequest.getOrderBy());
            if ("desc".equalsIgnoreCase(pageRequest.getOrderDirection())) {
                orderFields.add(orderField.desc());
            } else {
                orderFields.add(orderField.asc());
            }
        } else {
            // 默认按创建时间排序
            orderFields.add(TABLE_META.CREATED_TIME.desc());
        }
        
        // 查询分页数据
        List<TableMeta> records = dslContext.select()
                .from(TABLE_META)
                .where(TABLE_META.APP_ID.eq(appId)
                        .and(TABLE_META.DELETED_TIME.isNull()))
                .orderBy(orderFields)
                .limit(pageRequest.getPageSize())
                .offset((pageRequest.getPageNum() - 1) * pageRequest.getPageSize())
                .fetchInto(TableMeta.class);
        
        return PageResult.of(records, total, pageRequest.getPageNum(), pageRequest.getPageSize());
    }
}